package org.huzhp.listener;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.shared.Application;
import com.netflix.eureka.registry.InstanceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description: eureka服务状态监控
 * @Author: huzp
 * @CreateDate: 2020/3/12 12:48
 * @Version: 1.0
 */
@Component
public class EurekaStateChangeListener {

    private static Logger logger = LoggerFactory.getLogger(EurekaStateChangeListener.class);

    @Autowired
    private RegisterService registerService;

    @EventListener//(condition = "#event.replication==false")
    public void listen(EurekaInstanceCanceledEvent event) {
        // 服务断线事件
        String appName = event.getAppName();
        String serverId = event.getServerId();
        Objects.requireNonNull(appName, "服务名不能为空!");
        logger.info(">>>>>>> 失效服务:{},已被剔除!", serverId);
        Application application = ((InstanceRegistry) event.getSource()).getApplication(appName);
        if (application.size() < 2) {
            //相同应用只有全部失效才去取消网关路由
//            registerService.cancel(event.getAppName());
        }
    }

    @EventListener//(condition = "#event.replication==false")
    public void listen(EurekaInstanceRegisteredEvent event) {
        // 服务注册
        InstanceInfo instanceInfo = event.getInstanceInfo();
        String appName = instanceInfo.getAppName();
        Objects.requireNonNull(appName, "服务名不能为空!");
        logger.info(">>>>>>> 服务注册 服务名:{},端口号:{}", appName, instanceInfo.getPort());
//        registerService.register(appName);
    }

    @EventListener//(condition = "#event.replication==false")
    public void listen(EurekaInstanceRenewedEvent event) {
        // 服务续约
//        logger.info(">>>>>>>>>>>>>>>Server续约:" + event.getServerId());
    }

    @EventListener
    public void listen(EurekaRegistryAvailableEvent event) {
        // 注册中心启动
//        logger.info(">>>>>>>>>>>>>>>Server注册中心:" + event);
    }

    @EventListener
    public void listen(EurekaServerStartedEvent event) {
        // Server启动
//        logger.info(">>>>>>>>>>>>>>>Server启动:" + event);
    }
}
